package com.example.rbac.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.rbac.exception.CustomException;
import com.example.rbac.mapper.UserMapper;
import com.example.rbac.model.User;
import com.example.rbac.model.dto.UserInfoDTO;
import com.example.rbac.service.UserService;
import com.example.rbac.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private JwtUtils jwtUtils;
    
//    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    
    @Override
    public boolean register(User user) {
        // 检查用户名是否已存在
        User existingUser = userMapper.selectByUsername(user.getUsername());
        if (existingUser != null) {
            throw new CustomException("用户名已存在");
        }
        
        // 加密密码
//        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        // 设置创建时间
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);
        user.setCreateBy(0L);
        user.setUpdateBy(0L);
        user.setStatus(1); // 启用状态
        
        // 保存用户信息
        return this.save(user);
    }
    
    @Override
    public String login(String username, String password) {
        // 查询用户
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new CustomException("用户名不存在");
        }
        
        // 验证密码
        if (!password.equals(user.getPassword())) {
            throw new CustomException("密码错误");
        }
        
        // 检查用户状态
        if (user.getStatus() != 1) {
            throw new CustomException("用户已禁用");
        }
        
        // 获取用户角色和权限信息
        List<String> roles = userMapper.selectRoleKeysByUserId(user.getId());
        List<String> permissions = userMapper.selectPermissionKeysByUserId(user.getId());
        
        // 构建token中的额外信息
        Map<String, Object> claims = new HashMap<>();
        claims.put("roles", roles);
        claims.put("permissions", permissions);
        
        // 生成token
        return jwtUtils.generateToken(user.getId(), username, claims);
    }
    
    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }
    
    @Override
    public List<String> getRolesByUserId(Long userId) {
        return userMapper.selectRoleKeysByUserId(userId);
    }
    
    @Override
    public Set<String> getPermissionsByUserId(Long userId) {
        List<String> permissionList = userMapper.selectPermissionKeysByUserId(userId);
        return new HashSet<>(permissionList);
    }
    
    @Override
    public void logout(String token) {
        // 在实际应用中，这里可以将token加入黑名单或进行其他处理
        // 本示例暂不实现具体逻辑
    }
    
    // 根据用户信息创建脱敏的用户信息DTO
    public UserInfoDTO createUserInfoDTO(User user) {
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        BeanUtils.copyProperties(user, userInfoDTO);
        
        // 设置角色和权限信息
        userInfoDTO.setRoles(this.getRolesByUserId(user.getId()));
        userInfoDTO.setPermissions(this.getPermissionsByUserId(user.getId()));
        
        return userInfoDTO;
    }
}